﻿using ICSharpCode.SharpZipLib.Zip;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using ZenHR.AttData.DAL;
using ZenHR.AttData.Package.DataEntity;
using ZenHR.AttData.Package.Util;

namespace ZenHR.AttData.Package
{
    class Program
    {
        /// <summary>
        /// 清理内存
        /// </summary>
        [DllImport("kernel32.dll")]
        public static extern bool SetProcessWorkingSetSize(IntPtr proc, int min, int max);
        public static void FlushMemory()
        {
            try
            {
                GC.Collect();
                GC.WaitForPendingFinalizers();
                if (Environment.OSVersion.Platform == PlatformID.Win32NT)
                {
                    SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1);
                }
            }
            catch (Exception ex)
            {

            }
        }
        private static string m_Task_code;

       private static string error_mail = "";

       private static string _NodelJson="0";

       private static string _type = "1";


        static void Main(string[] args)
        {
            //ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            ServicePointManager.SecurityProtocol = SecurityProtocolType.SystemDefault | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13 | SecurityProtocolType.Ssl3;


            // ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 | (SecurityProtocolType)768 | (SecurityProtocolType)3072;

            // 单元测试用参数
            //ZenHR.AttData.Package.exe 3 CN51 202201241544 MsSql^1 evan.ju@touchimg.com
          //  args = new string[] { "10", "ML", "202306291455", "sftp^1", "evan.ju@touchimg.com", "ATT_DB1" };
            //ZenHR.AttData.Package.exe 3 CN51 202108250934 MsSql^1 evan.ju@touchimg.com


          // 10 ML 202306291455 sftp^1  ATT_DB1
            //接收传入的参数
            if (args.Length > 0)
            {

                string task_id = "";
                string task_code = "";
                string batch_id = "";
                string sql_type = "";
                string mail_address = "";
                string task_db = "";

                try
                {
                     task_id = args[0];
                     task_code = args[1];
                     batch_id = args[2];
                     sql_type = args[3];
                     mail_address = args[4];
                     task_db = args[5];
                }
                catch (Exception)
                {
                }

                try
                {
                    _NodelJson = args[6];
                }
                catch (Exception)
                {
                }

                try
                {
                    _type = sql_type.Split('^')[1];
                }
                catch (Exception)
                {
                }

                m_Task_code = task_code;

                //StringWriter sw = new StringWriter();
                ////Sets the System.Console.Out property to the specified System.IO.TextWriter object.
                ////设置控制台窗体输出
                //Console.SetOut(sw);

                try
                {
                    LogHelper.WriteLog("-----waiting for the packaging [TaskID:" + task_id + " TaskCode:" + task_code + " batch_id:" + batch_id + "sql_type:" + sql_type + "]", task_code);

                    BaseDAL _BaseDAL = new BaseDAL();
                    //DataTable _AppConfigData = _BaseDAL.GetAppConfig();
                    //error_mail = _AppConfigData.Rows[0]["error_mail"].ToString();

                    var _AttData = _BaseDAL.GetTaskAttData(task_db, batch_id, task_id, task_code);

                    //调用分批次上传
                    UpdataDataByPage(_AttData,  task_code,  sql_type,  batch_id,  task_id);

                    //分包轮询完成需要发送通知邮件给对饮采集任务人
                    string _error_file_path = AppDomain.CurrentDomain.BaseDirectory + "\\Att_Json\\" + DateTime.Now.ToString("yyyyMM");

                    DirectoryInfo folder = new DirectoryInfo(_error_file_path);

                    int _error_index = 0;

                    if (folder.Exists)
                    {
                        foreach (FileInfo file in folder.GetFiles("*.json"))
                        {
                            if (file.FullName.Contains(batch_id))
                            {
                                _error_index += 1;
                            }
                        }
                    }

                    //调用触发消费接口的时候才发邮件
                    if (Utility.GetConfig("IS_UploadDATA") == "1")
                    {
                        if (mail_address != "")
                        {
                            MailHelper.Send(mail_address, "TIMG考勤采集提醒：【" + task_code + "】", "<blockquote style=‘padding: 5px 10px; margin-top: 10px; margin-bottom: 10px; font-size: 14px; border-left-width: 8px; border-left-color: rgb(208, 229, 242); line-height: 1.4; background-color: rgb(241, 241, 241);‘>考勤卡点采集服务日志" + "[BatchID]: " + batch_id + "</blockquote><ul style=‘margin-top: 10px; margin-right: 0px; margin-left: 20px; padding: 0px;‘><li style=‘padding: 0px; margin: 0px; line-height: 1.8;‘>本次卡点采集时间：<span style=‘font-weight: 700; padding: 0px; margin: 0px;‘>" + DateTime.Now.ToLocalTime().ToString() + "</span></li><li style=‘padding: 0px; margin: 0px; line-height: 1.8;‘>本次卡点采集记录条数：<span style=‘font-weight: 700; padding: 0px; margin: 0px;‘>" + _AttData.Rows.Count.ToString() + "&nbsp;</span>条</li><li style=‘padding: 0px; margin: 0px; line-height: 1.8;‘>本次卡点失败批次数：<span style=‘font-weight: 700; padding: 0px; margin: 0px;‘>" + _error_index.ToString() + "&nbsp;</span>次（单次2000条）</li></ul>");

                        }

                    }

                    //DB3中参数当天TaskCode的历史批次记录
                    _BaseDAL.DelHisAttData(task_db, task_id, task_code, batch_id);

                    LogHelper.WriteLog("[TaskID]: " + task_id + " " + "[TaskCode]: " + task_code + " " + "[BatchID]: " + batch_id + " " + "[记录条数]：" + _AttData.Rows.Count.ToString(), task_code);
                }
                catch (Exception ex)
                {
                    var _error_info = "[TaskID]: " + task_id + " " + " [TaskCode]: " + task_code + " " + " [BatchID]: " + batch_id + " " + "[报错信息]：" + ex.Message;
                    LogHelper.WriteLog(_error_info, task_code);

                    //MailHelper.Send(error_mail, "upload to ZenHR error", _error_info);
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("----run to package error:" + ex.Message);
                }
                //finally
                //{
                    //LogHelper.WriteLog(sw.ToString(), task_code);
                //}

            }

            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine("----The process will shut down in 6 seconds!");

            Thread.Sleep(2000);
            Console.WriteLine("----6");

            Thread.Sleep(2000);
            Console.WriteLine("----4");

            Thread.Sleep(2000);
            Console.WriteLine("----3");

            Thread.Sleep(2000);

            return;
        }



        public static DataTable GetPagedTable(DataTable dt, int PageIndex, int PageSize)
        {
            if (PageIndex == 0) { return dt; }
            DataTable newdt = dt.Copy();
            newdt.Clear();
            int rowbegin = (PageIndex - 1) * PageSize;
            int rowend = PageIndex * PageSize;

            if (rowbegin >= dt.Rows.Count)
            { return newdt; }

            if (rowend > dt.Rows.Count)
            { rowend = dt.Rows.Count; }
            for (int i = rowbegin; i <= rowend - 1; i++)
            {
                DataRow newdr = newdt.NewRow();
                DataRow dr = dt.Rows[i];
                foreach (DataColumn column in dt.Columns)
                {
                    newdr[column.ColumnName] = dr[column.ColumnName];
                }
                newdt.Rows.Add(newdr);
            }
            return newdt;
        }

        /// <summary>
        /// 返回分页的页数
        /// </summary>
        /// <param name="count">总条数</param>
        /// <param name="pageye">每页显示多少条</param>
        /// <returns>如果 结尾为0：则返回1</returns>
        public static int PageCount(int count, int pageye)
        {
            int page = 0;
            int sesepage = pageye;
            if (count % sesepage == 0) { page = count / sesepage; }
            else { page = (count / sesepage) + 1; }
            if (page == 0) { page += 1; }
            return page;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="task_code"></param>
        /// <param name="sql_type"></param>
        /// <param name="batch_id"></param>
        /// <param name="task_id"></param>
        private static void UpdataDataByPage(DataTable dt,string task_code,string sql_type,string batch_id,string task_id)
        {
            var _page_count = 0;
            int pagenumber = 1;//分页的间隔
            int pagesize = 100000;//取分隔开来的第几个区块

            //获取分页数
            _page_count = PageCount(dt.Rows.Count, pagesize);

            for (int i = 0; i < _page_count; i++)
            {
                var row = dt.Rows.Cast<DataRow>();

                var _start_index = 1;

                if (i > 0)
                {
                    _start_index = i * pagesize;
                }
                else
                {
                    _start_index = 0;
                }

                var curRows = row.Skip(_start_index).Take(pagesize).ToArray();//按照间隔区分区块并获取指定区块数据

                try
                {
                    Console.WriteLine("Start:" + curRows[0][0].ToString() + "Count:" + curRows.Count().ToString());
                }
                catch (Exception)
                {
                }

                //上传ZenHR
                UploadDataToZenHRIF(curRows, task_code, sql_type, batch_id, task_id);
            }
        }


        /// <summary>
        // 调用ZenHR 执行数据的上传
        /// </summary>
        /// <param name="_AttData"></param>
        private static void UploadDataToZenHRIF(DataRow[] _att_data_row,string task_code,string sql_type,string batch_id,string task_id)
        {
            BaseDAL _BaseDAL = new BaseDAL();
            DataTable _AppConfigData = _BaseDAL.GetAppConfig();

            //加载授权配置信息
            var zenhr_if = _AppConfigData.Rows[0]["zenhr_if"].ToString();
            var zenhr_iftoken = _AppConfigData.Rows[0]["zenhr_iftoken"].ToString();
            var interface_id = _AppConfigData.Rows[0]["interface_id"].ToString();
            var oss_token = _AppConfigData.Rows[0]["oss_token"].ToString();
            var co_code = _AppConfigData.Rows[0]["co_code"].ToString();
            var key = _AppConfigData.Rows[0]["key"].ToString();

            var import_type = Utility.GetConfig("IMPORT_TYPE");
            var oss_type = Utility.GetConfig("OSS_TYPE");
            var is_UploadData = Utility.GetConfig("IS_UploadDATA");


            Console.WriteLine("sql_type:" + _type);

        

            //实例化数据对象
            var cardlist = DataTableToCardData(_att_data_row,sql_type);
       
            var size = 2000;
            var count = cardlist.Count / size;
            if ((cardlist.Count % size) != 0)
            {
                count = count + 1;
            }
            Console.WriteLine("--zenhr_if: " + zenhr_if);
            Console.WriteLine("--count: " + count.ToString());

            LogHelper.WriteLog("--zenhr_if: " + zenhr_if + " --count: " + count.ToString(), task_code);

            var tick = 0;
            Action<IEnumerable<cardData>> aa = null;
            aa = (rows) =>
            {
                //每个批次前都暂停3秒
                Thread.Sleep(new TimeSpan(0, 0, 3));

                tick++;
                var TOTALCOUNT = rows.Count();
                var datajson = Utility.ObjectToJson(rows.ToList());

                byte[] byteArray = Encoding.Default.GetBytes(datajson);
             
                var REQUEST_ID = Guid.NewGuid().ToString();
                DateTime ATT_DT = DateTime.Now;
                var SIGN = MD5.GETMD5(zenhr_iftoken + "|" + co_code + "|" + interface_id + "|" + REQUEST_ID + "|" + ATT_DT.ToString("yyyy/MM/dd") + "|" + TOTALCOUNT + "|" + oss_token + "|" + key);
                var requesturlParas = new List<string>();
                requesturlParas.Add("METHOD=BATCH_IMPORT_CLOCKINGDATA");
                requesturlParas.Add("TOKEN=" + Utility.UrlEncode(zenhr_iftoken));
                requesturlParas.Add("CO_CODE=" + Utility.UrlEncode(co_code));
                requesturlParas.Add("INTERFACE_ID=" + Utility.UrlEncode(interface_id));
                requesturlParas.Add("REQUEST_ID=" + Utility.UrlEncode(REQUEST_ID));
                requesturlParas.Add("ATT_DT=" + Utility.UrlEncode(ATT_DT.ToString("yyyy/MM/dd")));
                requesturlParas.Add("TOTALCOUNT=" + TOTALCOUNT);
                requesturlParas.Add("SIGN=" + Utility.UrlEncode(SIGN));
                requesturlParas.Add("OSS_TOKEN=" + Utility.UrlEncode(oss_token)); 
                requesturlParas.Add("SYSTEM_NO=" + Utility.UrlEncode("100001"));
                requesturlParas.Add("is_async=1");
                requesturlParas.Add("TYPE=" + _type);
                requesturlParas.Add("CLOCKING_TYPE=10");  //8代表手动导入  10代表接口导入
                
                //requesturlParas.Add("IMPORT_TYPE=2");
                //requesturlParas.Add("DATAURL="+Utility.UrlEncode("https://xxxx./aa1.zip"));

                //启用一次性上传模式
                if (import_type == "2")
                {
                    MemoryStream stream = new MemoryStream(byteArray);

                    var sFilePath = AppDomain.CurrentDomain.BaseDirectory + @"Zip_File\"; 
                    var sFileName = task_code + "_" + task_id + "_" + batch_id + "_" + DateTime.Now.ToString("yyyyMMddHHmmss");

                    ZipHelper.CreateFile(sFilePath, sFileName + ".json", datajson);

                    //生成的文件绝对路径
                    var zipfilename = sFilePath + "\\" + sFileName + ".zip";
                    var jsonfilename = sFilePath + "\\" + sFileName + ".json";

                    //ZipHelper _zp = new ZipHelper();
                    //_zp.ZipFile(jsonfilename, zipfilename);

                    ZipZenHRHepler.CreateZipFile(zipfilename, sFileName + ".json", jsonfilename);

                    var _catch_Upload_index = 1;

                    var log = "";
                    var temp_uri = "";
                    var fixed_uri = "";

                Labell:
                    //每个批次前都暂停3秒

                    Thread.Sleep(new TimeSpan(0, 0, 3));

                    try
                    {
                        if (Utility.GetConfig("Aliyun_OSS_AccessKeyID") == "aws")
                        {
                            temp_uri = AwsS3Helper.AwsUpload(@"CLOCKDATA/" + sFileName + ".zip", zipfilename);
                        }

                        switch (oss_type)
                        {
                            case "aws":
                                temp_uri = AwsS3Helper.AwsUpload(@"CLOCKDATA/" + sFileName + ".zip", zipfilename);
                                break;

                            case "aliyun":

                                //阿里云OSS暂时关闭  --osspath  测试环境 Jabil  正式环境 Jabil-PRD
                                //var osspath = string.Format(Utility.GetConfig("Aliyun_OSS_OssPath")+@"/{0}/{1}/{2}/{3}", DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, Path.GetFileName(zipfilename));

                                //阿里云OSS放根目录，服务器端5分钟轮询服务取
                                var osspath = string.Format(Utility.GetConfig("Aliyun_OSS_OssPath") + @"/{0}", Path.GetFileName(zipfilename));

                                var accessId = Utility.GetConfig("Aliyun_OSS_AccessKeyID");
                                var accessKey = Utility.GetConfig("Aliyun_OSS_AccessSecret");
                                var endpoint = Utility.GetConfig("Aliyun_OSS_HostName");
                                var Aliyun_OSS_BuckName = Utility.GetConfig("Aliyun_OSS_BuckName");

                                MultipartUploadSample.accessId = accessId;
                                MultipartUploadSample.accessKey = accessKey;
                                MultipartUploadSample.endpoint = endpoint;

                                //1.将压缩文件上传至OSS
                                MultipartUploadSample.UploadMultipart(Aliyun_OSS_BuckName, osspath, zipfilename, 1024 * 1024 * 10);

                                //获取AliOSS上传
                                MultipartUploadSample.getObjectBySignedUrl2(Aliyun_OSS_BuckName, osspath, 24 * 7, out log, out temp_uri, out fixed_uri);

                                break;
                            default:

                                LogHelper.WriteLog("OSS Setting Error:Not find config", task_code);
                                break;
                        }

                    }
                    catch (WebException ex)
                    {
                        _catch_Upload_index += 1;   //重试次数累加

                        LogHelper.WriteLog("Web File UploadMultipart WebException:" + ex.Message, task_code);

                        if (_catch_Upload_index < 3)
                        {
                            goto Labell;
                        }
                    }
                    catch (Exception ex)
                    {
                        _catch_Upload_index += 1;   //重试次数累加

                        LogHelper.WriteLog("Web File UploadMultipart Exception:" + ex.Message, task_code);

                        if (_catch_Upload_index < 3)
                        {
                            goto Labell;
                        }
                    }

                    //返回为空
                    if (log == "")
                    {
                        //先把aliyunoss下载地址保存下来
                        LogHelper.WriteLog("Web File Url:" + temp_uri, task_code);

                        try
                        {
                            if (_NodelJson != "1")
                            {

                                File.Delete(jsonfilename);
                                File.Delete(zipfilename);
                            }

                        }
                        catch (Exception)
                        {
                        }
                    }
                    else
                    {
                        LogHelper.WriteLog("Web File UploadMultipart Log:" + log, task_code);
                    }

                    requesturlParas.Add("IMPORT_TYPE=2");
                    requesturlParas.Add("DATAURL=" + Utility.UrlEncode(temp_uri));
                }
                else
                {
                    requesturlParas.Add("IMPORT_TYPE=1");
                }

                var Requesturl = zenhr_if + "?" + string.Join("&", requesturlParas);


             

               // Console.WriteLine("--Requesturl: " + Requesturl);

                requesturlParas.Clear();

                //Console.ForegroundColor = ConsoleColor.Green;
                //Console.WriteLine("Uploading... ");
               
                //调用外部接口，如发生异常记录日志
                var _catch_index = 1;  //对于当前批次记录重试次数

                if (is_UploadData == "1")
                {
                    //调用上传（失败累计递归）
                    Run_Webclient_UploadData(Requesturl, byteArray, _catch_index, task_code, tick, TOTALCOUNT, datajson, batch_id, import_type);

                }
                else
                {
                    LogHelper.WriteLog("No Run_Webclient_UploadData.", task_code);
                }

                //上传成删除文件
                //DEBUG:测试先输出一下文件
                //LogHelper.WriteAttJson(datajson,task_code + '_' + tick.ToString() + '_' + TOTALCOUNT.ToString());

                //回调信息暂不处理  resultstr 将来需要的时候在用
                datajson = null;

            };

            if (import_type == "2")
            {
                //完整调用一次
                aa(cardlist);
            }
            else
            {
                //每2000条切分调用多次
                for (int i = 0; i < count; i++)
                {
                    //Console.WriteLine("curlist... " + i.ToString());
                    var curlist = cardlist.Skip(i * size).Take(size);
                    if (curlist != null && curlist.Count() > 0)
                    {
                        aa(curlist);
                    }
                }
            }

            cardlist = null;
            FlushMemory();
        }


        /// <summary>
        /// 执行上传（支持重试次数）
        /// </summary>
        /// <param name="Requesturl"></param>
        /// <param name="webclient"></param>
        /// <param name="byteArray"></param>
        private static void Run_Webclient_UploadData(string Requesturl,byte[] byteArray, int _catch_index,string task_code,int tick,int TOTALCOUNT,string datajson,string batch_id,string import_type)
        {
            try
            {
                if (_catch_index > 3)
                {
                    //Console.WriteLine("Upload Failed:" + "The number of retries exceeded!");  //输出反馈日志

                    LogHelper.WriteLog("Upload Failed:" + "The number of retries exceeded!", task_code);


                    //重试3次以上还未成功则记录日志存方在本地目录下
                    LogHelper.WriteAttJson(datajson, task_code + '_' + tick.ToString() + '_' + _catch_index.ToString() + '_' + TOTALCOUNT.ToString(), batch_id);
                }
                else
                {
                   // Thread.Sleep(new TimeSpan(0, 0, 3));
                    Uri _aa = new Uri(Requesturl);

                    LogHelper.WriteLog("webclient.Requesturl：" + Requesturl, task_code);

                    //注册回调事件(异步)
                    //webclient.UploadDataCompleted += Webclient_UploadDataCompleted;
                    //webclient.UploadDataAsync(_aa, byteArray);

                    var s = new Stopwatch();
                    s.Start();
                    //webclient.UploadData(_aa, byteArray);
                    LogHelper.WriteLog("webclient.UploadData_Start：" + DateTime.Now.ToString(), task_code);
                    LogHelper.WriteLog("webclient.AbsoluteUri：" + _aa.AbsoluteUri, task_code);

                    TWebClient _webclient = new TWebClient();
                    _webclient.Timeout = 10 * 60 * 1000;

                    _webclient.Encoding = UTF8Encoding.UTF8;

                    //如ZIP模式则直接调用触发既可
                    if (import_type == "2")
                    {
                        var _dl_str = _webclient.DownloadString(_aa);
                        s.Stop();
                        LogHelper.WriteLog("webclient.UploadData_END：" + s.ElapsedMilliseconds + Utility.UrlEncode(_dl_str), task_code);
                    }
                    else
                    {

                        //服务器端调用数据上传
                        byte[] fileb = _webclient.UploadData(_aa, byteArray);

                        string str = System.Text.Encoding.UTF8.GetString(fileb);

                        s.Stop();
                        LogHelper.WriteLog("webclient.UploadData_END：" + s.ElapsedMilliseconds + " " + str, task_code);

                    }

                    //string res = Encoding.UTF8.GetString(fileb);   //接收反馈信息
                    //Console.WriteLine("Upload Completed [" + task_code + '_' + tick.ToString() + '_' + _catch_index.ToString() + '_' + TOTALCOUNT.ToString() + "]" );  //输出反馈日志
                    LogHelper.WriteLog("Upload Completed [" + task_code + '_' + tick.ToString() + '_' + _catch_index.ToString() + '_' + TOTALCOUNT.ToString() + "]", task_code);

                }
            }
            catch (WebException ex)
            {
                if (ex.Response != null)
                {
                    var respSteam = ex.Response.GetResponseStream();
                    if (respSteam != null && respSteam.Length > 0)
                    {
                        var responseText = new StreamReader(respSteam).ReadToEnd();

                        var _error_info = "webclient.UploadData-报错:" + task_code + '_' + tick.ToString() + '_' + _catch_index.ToString() + '_' + TOTALCOUNT.ToString() + " " + "[报错信息]：" + responseText;
                        LogHelper.WriteLog(_error_info, task_code);

                    }
                    else
                    {
                        var _error_info = "webclient.UploadData respSteam Null-报错:" + task_code + '_' + tick.ToString() + '_' + _catch_index.ToString() + '_' + TOTALCOUNT.ToString() + " " + "[报错信息]：" + "服务器方法调用失败！";
                        LogHelper.WriteLog(_error_info, task_code);
                    }

                }
                else {

                    var _error_info = "webclient.UploadData-Response Null 报错:" + task_code + '_' + tick.ToString() + '_' + _catch_index.ToString() + '_' + TOTALCOUNT.ToString() + " " + "[报错信息]：" +ex.Message;
                    LogHelper.WriteLog(_error_info, task_code);

                }

                _catch_index += 1;   //重试次数累加
                Run_Webclient_UploadData(Requesturl, byteArray, _catch_index, task_code, tick, TOTALCOUNT, datajson, batch_id, import_type);

            }
            catch (Exception ex)
            {
                //报错的情况下开始递归重试
                try
                {
                    var _error_info = "上传批次报错:" + task_code + '_' + tick.ToString() + '_' + _catch_index.ToString() + '_' + TOTALCOUNT.ToString() + " " + "[报错信息]：" + ex.Message;
                    LogHelper.WriteLog(_error_info, task_code);

                    _catch_index += 1;   //重试次数累加
                    Run_Webclient_UploadData(Requesturl,byteArray,_catch_index,task_code,tick,TOTALCOUNT,datajson,batch_id, import_type);
                }
                catch (Exception)
                {
                }
            }
        }

        private static void Webclient_UploadDataCompleted(object sender, System.Net.UploadDataCompletedEventArgs e)
        {
            byte[] data = (byte[])e.Result;
            string reply = System.Text.Encoding.UTF8.GetString(data);

            // Console.WriteLine(reply);

            LogHelper.WriteLog(reply, m_Task_code);
        }

        private static string FirstTwenty(string input)
        {
            return input.Length > 200 ? input.Substring(0, 200) : input;
        }



        /// <summary>
        /// 
        /// </summary>
        /// <param name="p_AttData"></param>
        /// <returns></returns>
        private static List<cardData> DataTableToCardData(DataRow[] _att_data_row, string sql_type)
        {

          

            var cardlist = new List<cardData>();
            foreach (DataRow item in _att_data_row)
            {

                //var _type = string.Format("{0}", item["emp_code"]) != "" ? "1" : "2";

                try
                {
                    _type = sql_type.Split('^')[1];
                }
                catch (Exception)
                {
                    _type = "1";
                }

                string _emp_code = item["emp_code"].ToString();
                if (_emp_code.Contains("("))
                {
                    _emp_code = _emp_code.Split('(')[0];
                }


                var model = new cardData();
                model.CHECK_TYPE = string.Format("{0}", item["inorout"]);
                model.CLOCKING_CODE = "";
             
                model.CLOCKING_TIME = string.Format("{0:yyyy/MM/dd HH:mm:ss}", item["check_time"]);
                model.NO_ATTTRACKING = string.Format("{0}", item["extend_info"]) != "" ? "1": "0" ;
                model.REMARKS = string.Empty;
                model.TYPE = string.Format("{0}", _type) ;   //根据返回数据自动判断是工号还是卡号
                model.CODE = string.Format("{0}", _emp_code) != "" ? string.Format("{0}", _emp_code) : string.Format("{0}", item["card_number"]);
                cardlist.Add(model);
            }
            return  cardlist;
        }


        /// <summary>
        /// 数据转存本地CSV
        /// </summary>
        /// <param name="table"></param>
        /// <param name="file"></param>
        /// <param name="Title"></param>
        public static void dataTableToCsv(DataTable table, string file, string Title)
        {
            FileInfo fi = new FileInfo(file);
            string path = fi.DirectoryName;
            string name = fi.Name;
            //\/:*?"<>|
            //把文件名和路径分别取出来处理
            name = name.Replace(@"\", "＼");
            name = name.Replace(@"/", "／");
            name = name.Replace(@":", "：");
            name = name.Replace(@"*", "＊");
            name = name.Replace(@"?", "？");
            name = name.Replace(@"<", "＜");
            name = name.Replace(@">", "＞");
            name = name.Replace(@"|", "｜");
            string title = "";

            FileStream fs = new FileStream(path + "\\" + name, FileMode.Create);
            StreamWriter sw = new StreamWriter(new BufferedStream(fs), System.Text.Encoding.Default);

            title += Title + ",";
            for (int i = 1; i < table.Columns.Count; i++)
            {
                title += ",";
            }
            title = title.Substring(0, title.Length - 1) + "\n";
            sw.Write(title);
            title = "";

            for (int i = 0; i < table.Columns.Count; i++)
            {
                title += table.Columns[i].ColumnName + ",";
            }
            title = title.Substring(0, title.Length - 1) + "\n";
            sw.Write(title);

            foreach (DataRow row in table.Rows)
            {
                if (row.RowState == DataRowState.Deleted) continue;
                string line = "";
                for (int i = 0; i < table.Columns.Count; i++)
                {
                    line += row[i].ToString().Replace(",", "") + ",";
                }
                line = line.Substring(0, line.Length - 1) + "\n";

                sw.Write(line);
            }

            sw.Close();
            fs.Close();
        }

        

        


    }
}
